package fw.protocol.zigbee.bundle;

import it.cnr.isti.zigbee.api.Cluster;
import it.cnr.isti.zigbee.ha.cluster.impl.OnOffImpl;
import it.cnr.isti.zigbee.zcl.library.api.general.OnOff;
import it.cnr.isti.zigbee.zcl.library.impl.ClusterImpl;
import it.cnr.isti.zigbee.zcl.library.impl.core.EmptyPayloadCommand;
import it.cnr.isti.zigbee.zcl.library.impl.core.ZCLFrame;
import it.cnr.isti.zigbee.zcl.library.impl.general.OnOffCluster;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

import es.unizar.howlab.core.zigbee.telegesis.driver.Driver;
import es.unizar.howlab.core.zigbee.telegesis.driver.ZigbeeDevice;

public class DriverManager implements ServiceTrackerCustomizer {

	private BundleContext bc;
	public DriverManager(BundleContext bc) {
		this.bc= bc;
	}
	
	private static EmptyPayloadCommand CMD_ON = new EmptyPayloadCommand()
	.setId(OnOff.ON_ID)
	.setClientServerDirection(true)
	.setClusterSpecific(true)
	.setManufacturerExtension(false);
	
	public Object addingService(ServiceReference sf) {
		Driver driver = (Driver) bc.getService(sf);
		System.out.println("discover: " + driver.getNetworkCoordinator().discoverZigbeeDevices());
		ZigbeeDevice[] all = driver.getNetworkCoordinator().getZigbeeDevices();
		for(int i = 0 ; i < all.length ; i++){
			System.out.println("My Devices: " + all[i]);
		}
		ZigbeeDevice device = all[1];
		OnOffCluster on = new OnOffCluster(null);
		OnOffImpl onOff = new OnOffImpl(null);
		System.out.println("device id:" + all[0].getDeviceId());
		System.out.println("device id:" + device.getDeviceId());
//		bc.getServiceReference(arg0)
		ZCLFrame inFrame = new ZCLFrame(CMD_ON, true);
		ClusterImpl input = new ClusterImpl((short) 0,inFrame);
//		all[i].put(reference, device);
		System.out.println("input.getClusterMsg(): " + input.getClusterMsg());
		for (int i = 0; i < input.getClusterMsg().length; i++) {
			System.out.println(String.format("0x%02X", input.getClusterMsg()[i]));
		}
		device.sendMessage(device.getProfileId(), device.getDeviceId(), input.getClusterMsg());
		return device;
	}

	public void modifiedService(ServiceReference arg0, Object arg1) {
		// TODO Auto-generated method stub
		
	}

	public void removedService(ServiceReference arg0, Object arg1) {
		// TODO Auto-generated method stub
		
	}

}
